#include "database_service.h"
#include "utils.h"
#include <iostream>
#include <cstring>
#include <mysql/mysql.h>
DatabaseService::DatabaseService(MySQLConnectionPool& pool)
    : conn_pool(pool) {
    // 构造函数的实现代码
}
void DatabaseService::insertData(const std::string& name, const std::string& email) {
    MYSQL* conn = conn_pool.getConnection();

    MYSQL_STMT* stmt = mysql_stmt_init(conn);
    if (!stmt) {
        handleError(conn, "mysql_stmt_init() failed");
    }

    const char* insertQuery = "INSERT INTO finace_calculate (name, email) VALUES (?, ?)";
    if (mysql_stmt_prepare(stmt, insertQuery, strlen(insertQuery)) != 0) {
        handleError(conn, "mysql_stmt_prepare() failed");
    }

    MYSQL_BIND bind[2];
    memset(bind, 0, sizeof(bind));

    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = const_cast<char*>(name.c_str());
    bind[0].buffer_length = name.length();

    bind[1].buffer_type = MYSQL_TYPE_STRING;
    bind[1].buffer = const_cast<char*>(email.c_str());
    bind[1].buffer_length = email.length();

    if (mysql_stmt_bind_param(stmt, bind)) {
        handleError(conn, "mysql_stmt_bind_param() failed");
    }

    if (mysql_stmt_execute(stmt)) {
        handleError(conn, "mysql_stmt_execute() failed");
    }

    mysql_stmt_close(stmt);
    conn_pool.releaseConnection(conn);
}

void DatabaseService::readData() {
    MYSQL* conn = conn_pool.getConnection();

    if (mysql_query(conn, "SELECT COUNT(*) FROM finace_calculate")) {
        handleError(conn, "Count query failed");
    }

    MYSQL_RES* result = mysql_store_result(conn);
    if (!result) {
        handleError(conn, "Failed to get count result");
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (row) {
        std::cout << "Total records: " << row[0] << std::endl;
    }

    mysql_free_result(result);
    conn_pool.releaseConnection(conn);
}